package com.cnswhy.cloud.server.core.channel.service;

import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.utils.CnswhyUtil;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.core.constant.RedisConstant;
import com.cnswhy.cloud.server.core.entity.SysConfig;
import com.cnswhy.cloud.server.core.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AliRoutePayService {
    @Autowired
    SysConfigService sysConfigService;
    @Autowired
    RedisService redisService;
    public String pay(String orderId,Long transAmt,String body){
        SysConfig sysConfig = sysConfigService.getOne(Wraps.<SysConfig>lbQ().eq(SysConfig::getConfigKey, RedisConstant.ali_route_config));
        String notifyUrl = (String) redisService.hget(RedisConstant.SYS_CONFIG_2,
                RedisConstant.ali_route_notify);
        String frontUrl = (String) redisService.hget(RedisConstant.SYS_CONFIG_2,
                RedisConstant.ali_route_front);
        String merchId = sysConfig.getConfigValue();
        String branchCode = sysConfig.getConfigRules();
        String key = sysConfig.getValidateRules();
        Map<String, String> request1 = new HashMap<>();
        request1.put("orderId", orderId);
        request1.put("amount", transAmt.toString());
        request1.put("notifyUrl",notifyUrl);
        request1.put("frontUrl",frontUrl);
        request1.put("branchCode",branchCode);
        request1.put("merchId",merchId);
        request1.put("usePool","1");
        request1.put("fromIp","1");
        request1.put("body",body);
        request1.put("transType", "300");
        request1.put("sign",md5(orderId + transAmt.toString() +merchId + key).toLowerCase());
        log.info(createRequest(request1));
        String responseString = doPost("http://apidf.srsky.cn/php/createOrder.do",createRequest(request1));
        log.info(responseString);
        return responseString;
    }
    public  String transQuery(String orderId){
        SysConfig sysConfig = sysConfigService.getOne(Wraps.<SysConfig>lbQ().eq(SysConfig::getConfigKey, RedisConstant.ali_route_config));
        String notifyUrl = (String) redisService.hget(RedisConstant.SYS_CONFIG_2,
                RedisConstant.ali_route_notify);
        String frontUrl = (String) redisService.hget(RedisConstant.SYS_CONFIG_2,
                RedisConstant.ali_route_front);
        String merchId = sysConfig.getConfigValue();
        String branchCode = sysConfig.getConfigRules();
        String key = sysConfig.getValidateRules();
        String url = "http://apidf.srsky.cn/php/php/transQuery.do";
        Map<String, String> request = new HashMap<>();
        request.put("orderId",orderId);
        request.put("branchCode",branchCode);
        request.put("merchId",merchId);
        request.put("sign",md5(orderId  +merchId + key).toLowerCase());
        log.info(createRequest(request));
        String repsonse = doPost(url,createRequest(request));
        log.info(repsonse);
        return repsonse;
    }

    private static final String HEX_CHARS = "0123456789abcdef";
    private static final String HEX_CHARS_UPPER = "0123456789ABCDEF";
    public static String md5(String data){
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        byte[] b = md.digest(data.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            sb.append(HEX_CHARS_UPPER.charAt(b[i] >>> 4 & 0x0F));
            sb.append(HEX_CHARS_UPPER.charAt(b[i] & 0x0F));
        }
        return sb.toString();
    }
    public static String doPost(String url, String content) {
        /**
         * 发送请求
         */
        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;

            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(content.length()));
            /**
             * 链接超时
             * 读取超时
             */
            httpURLConnection.setConnectTimeout(60 * 1000);
            httpURLConnection.setReadTimeout(60 * 1000);

            outputStream = httpURLConnection.getOutputStream();
            outputStreamWriter = new OutputStreamWriter(outputStream);
            outputStreamWriter.write(content);
            outputStreamWriter.flush();

            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);
            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
            return resultBuffer.toString();
        } catch (Exception ex) {
        } finally {
            try {
                if (outputStreamWriter != null) {
                    outputStreamWriter.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception ex) {
            }
        }
        return null;
    }

    public static String createRequest(Map<String, String> parm) {
        StringBuffer rtn = new StringBuffer();
        for (String s : parm.keySet()) {
            try {
                if (parm.get(s) != null) {
                    rtn.append(s).append("=").append(URLEncoder.encode(parm.get(s), "UTF-8")).append("&");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return rtn.toString();
    }
}
